package cool.mtc.minghe.service.service.sys.role.impl;

import cool.mtc.core.exception.ServiceException;
import cool.mtc.minghe.data.entity.sys.role.RolePermissionDO;
import cool.mtc.minghe.data.model.sys.role.permission.dto.RolePermissionDTO;
import cool.mtc.minghe.data.model.sys.role.permission.form.RolePermissionForm;
import cool.mtc.minghe.service.mapper.sys.role.RolePermissionMapper;
import cool.mtc.minghe.service.service.BaseServiceImpl;
import cool.mtc.minghe.service.service.sys.role.RolePermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 明河
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RolePermissionServiceImpl extends BaseServiceImpl implements RolePermissionService {
    private final RolePermissionMapper rolePermissionMapper;

    @Override
    @Transactional
    public void insert(RolePermissionForm form) {
        RolePermissionDO rolePermissionDO = form.transToDO();
        rolePermissionDO.setCreator(userId());
        rolePermissionMapper.insert(rolePermissionDO);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        if (null == id) {
            return;
        }
        RolePermissionDO rolePermissionDO = rolePermissionMapper.selectById(id);
        if (null == rolePermissionDO) {
            return;
        }
        this.handleCheckCanDelete(rolePermissionDO);
        rolePermissionMapper.deleteById(id);
    }

    /**
     * 检查是否可以删除
     */
    private void handleCheckCanDelete(RolePermissionDO rolePermissionDO) {
        if (Boolean.TRUE.equals(rolePermissionDO.getPreset())) {
            throw new ServiceException("preset.delete.not_allow");
        }
    }

    @Override
    public List<RolePermissionDTO> listPermissionByRoleIdo(long roleId) {
        return rolePermissionMapper.listPermissionByRoleId(roleId);
    }
}
